<?php

class Upload extends CI_Controller {

	var $page = 'upload_form';
	var $action = '';


	public function index(){
		$data['error'] = "";
		$data['uploadedFiles'] = $this->db->query("select * from uploaded_files where valid = 1" );

		$this->admin($data,null);

	}

	function download($filename){
		$dataq = file_get_contents("./uploadedFiles/txt/$filename"); // Read the file's contents
		$name = 'transactionfiles.txt';

		force_download($filename , $dataq);

	}

	function do_upload()
	{
		$config['upload_path'] = './uploadedFiles/txt/';
		$config['allowed_types'] = 'gif|jpg|png|txt|xls|xlsx';

		$this->load->library('upload', $config);


		if ( ! $this->upload->do_upload())
		{
			$data['errorMessage'] = $this->upload->display_errors();

			$data['uploadedFiles'] = $this->db->query("select * from uploaded_files where valid = 1" );

			$this->admin($data,null);
		}
		else
		{
			$data['upload_data'] = $this->upload->data();

			$filename =  $data['upload_data']['file_name'];
			$rawname =  $data['upload_data']['raw_name'];
			$orig_name = $data['upload_data']['orig_name'];
			$remarks = $_REQUEST['remarks'];

			$this->db->query("INSERT INTO  uploaded_files (id ,file_name ,orig_name ,remarks ,valid,createdon , updatedon) VALUES(NULL ,'$filename'  , '$orig_name' ,'$remarks', 1 ,NOW(), NOW())");
			$data['successMessage'] = "File was Successfully Uploaded";
			$data['uploadedFiles'] = $this->db->query("select * from uploaded_files where valid = 1" );


			$this->admin($data,null);
		}
	}


	public function delete($id){

		$data['deleteId'] = $id;
			
		$query = $this->db->query("update uploaded_files set valid = false  where id = $id limit 1" );
			
		$this->createLog('FILES' , 'DELETED' ,  "Deleted File record where id = $id");
			
		$this->index();
			
	}

	function loadUploadedFiles(){
		return get_filenames('./uploadedFiles/txt/');
	}
}
?>